<?php


namespace app\unify\validate;


use think\Validate;
use app\unify\model\User as UserModel;

class User extends Validate
{

    const READ = 'Read';
    const LOGIN = 'Login';
    const REGISTER = 'register';

    const SAVE = 'Save';
    const UPDATE = "Update";
    const UPDATE_FIELD = 'UpdateField';
    const UPDATE_PASSWORD = "UpdatePassword";

    const DELETE = 'Delete';
    const INDEX = 'Index';
    const EDIT = "Edit";

    protected $rule = [
        'ids|编号集合' => 'require|array',
        'id|编号' => 'require|string',
        'nick|昵称' => 'require|length:1,15',
        'username|账户' => 'require|length:5,15|regex:/^[a-zA-Z][a-zA-Z0-9]*$/|checkUsernameUnique',
        'oldPassword|旧密码' => 'require|length:32',
        'password|密码' => 'requireWith:passwordAgain|length:32',
        'passwordAgain|确认密码' => 'requireWith:password|length:32',
        'mobile|联系手机号' => 'length:11|regex:/^1\d{10}$/',
        'email|联系邮箱' => 'email',
        'roleList|角色' => 'require|array',
        'status|状态' => 'require|in:' . UserModel::STATUS_ENABLE . ',' . UserModel::STATUS_DISABLE,
        'field|字段名' => 'require|in:status',
        'value|字段值' => 'require',
        'homePage|默认首页' => 'require',
    ];

    protected $scene = [
        self::READ => ['id'],
        self::SAVE => ['nick', 'username', 'password', 'passwordAgain', 'mobile', 'email', 'roleList', 'status', 'homePage'],
        self::UPDATE => ['id', 'nick', 'username', 'password', 'passwordAgain', 'mobile', 'email', 'roleList', 'status', 'homePage'],
        self::UPDATE_PASSWORD => ['oldPassword', 'password', 'passwordAgain'],
        self::UPDATE_FIELD => ['ids', 'field', 'value'],
        self::DELETE => ['ids'],
    ];

    public function sceneEdit(){
        return $this->only( ['nick', 'mobile', 'mobile'])->remove("nick", 'require');
    }

    public function sceneLogin()
    {
        return $this->only(['username', 'password'])->remove('username', 'checkUsernameUnique');
    }

    public function checkUsernameUnique($value, $rule, $data)
    {
        $where = [
            ['username', '=', $value]
        ];

        $id = $data[UserModel::getPrimaryKey()] ?? null;
        if ($id) {
            $where[] = [UserModel::getPrimaryKey(), '<>', $id];
        }

        if (!UserModel::where($where)->findOrEmpty()->isEmpty()) {
            return '登录账户已存在';
        }

        return true;
    }

}